
#import "Touches.h"
#import <objc/runtime.h>

@interface UIView (JMWhenTappedBlocks_Private)

- (void)runBlockForKey:(void *)blockKey;
- (void)setBlock:(JMWhenTappedBlock)block forKey:(void *)blockKey;

@end

@implementation UIView (JMWhenTappedBlocks)

static char kWhenTappedBlockKey;

- (void)addTouches:(JMWhenTappedBlock)block
{
    [self setBlock:block forKey:&kWhenTappedBlockKey];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchfunc)];
    tapGesture.delegate = self;
    tapGesture.numberOfTapsRequired = 1;
    tapGesture.numberOfTouchesRequired = 1;
    [self addGestureRecognizer:tapGesture];
}

- (void)touchfunc
{
    [self runBlockForKey:&kWhenTappedBlockKey];
}

- (void)runBlockForKey:(void *)blockKey
{
    JMWhenTappedBlock block = objc_getAssociatedObject(self, blockKey);
    if (block) block();
}

- (void)setBlock:(JMWhenTappedBlock)block forKey:(void *)blockKey
{
    self.userInteractionEnabled = YES;
    objc_setAssociatedObject(self, blockKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end
